package com.jl.applet;

import opencard.core.service.CardServiceException;
import opencard.opt.applet.AppletID;
import opencard.opt.applet.AppletInfo;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;

import com.jl.card.Card;
import com.jl.card.ICard;
import com.jl.util.HexUtil;

public class ISOAppletJSProxy extends ScriptableObject implements IApplet {

	private IApplet applet;
	private AppletID aid;
	private Card card;

	public ISOAppletJSProxy() {
	}

	@JSConstructor
	public ISOAppletJSProxy(Object _card, String aid) {
		this();
		this.card = (Card) Context.jsToJava(_card, Card.class);
		this.aid = new AppletID(HexUtil.parseHexToByteArray(aid));
		this.applet = card.getProvider().getApplet(this.card);
	}

	@JSFunction
	public boolean select(boolean reset) {
		if (reset) {
			card.reset(false);
		}
		try {
			this.select(card, aid);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public String getClassName() {
		return "Applet";
	}

	@Override
	public AppletInfo select(ICard card, AppletID aid)
			throws CardServiceException {
		return applet.select(card, aid);
	}

}
